const path = require('path');
const spawn = require('child_process').spawn;
const key = "myWebhookKey";

const rumCommand = ((cmd, args, callback) => {
    const child = spawn(cmd, args);
    let resp = "";

    child.stdout.on('data', (buffer) => { resp += buffer.toString()})
    child.stdout.on('end', function(){ callback && callback(resp) })
});

class WebhookController {
    server(ctx){
        if(ctx.headers && ctx.headers['x-gitee-token'] == key){
            if(ctx.request.body){
                if(ctx.request.body.hook_name == "push_hooks"){
                    console.log('server自动部署开始...')
                    ctx.body = '开始执行shell!'
                    rumCommand('sh', [path.resolve(__dirname, '../bin/server.sh')], (e) => {})
                }else{
                    ctx.body = 'error: hook_name 不是push_hooks'
                }
            }else{
                ctx.body = 'error: 没有body参数!';
            }
        }else{
            ctx.body = 'error: x-gitee-token: key值错误错误!';
        }
    }
}

module.exports = new WebhookController();